package com.example.demo.scheduledtask;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.demo.common.Constant;
import com.example.demo.mapper.AsyncWorkorderMapper;
import com.example.demo.mapper.ProcurementDetailsRecodeMapper;
import com.example.demo.mapper.PurchaseReceiptDetailsRecodeMapper;
import com.example.demo.mapper.WmsPurchaseMapper;
import com.example.demo.utils.SoapXmlUtil;
import com.example.demo.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : Zhang.yt
 * @date : 2024/3/5
 */
@Component
@Slf4j
@DS("wms")
public class TestTask {
    @Resource
    private WmsPurchaseMapper wmsPurchaseMapper;

    @Resource
    private AsyncWorkorderMapper asyncWorkorderMapper;

    @Resource
    private ProcurementDetailsRecodeMapper procurementDetailsRecodeMapper;

    @Resource
    private PurchaseReceiptDetailsRecodeMapper purchaseReceiptDetailsRecodeMapper;

    @Autowired
    private SoapXmlUtil soapXmlUtil;

//    public void pickingOutCallback() {
//        //查询没有回调的数据
//        PickingOutVo pickingOutCallback = wmsPurchaseMapper.getPickingOutCallbackTest();
//        List<String> outnoList = pickingOutCallback.stream().map(PickingOutVo::getSfda014).collect(Collectors.toList());
//        if (CollectionUtils.isEmpty(outnoList)) {
//            return;
//        }
//        //根据没有回调的数据查询细表
//        List<PickingOutVoReceiptListVo> pickingOutVoReceiptList = wmsPurchaseMapper.getPickingOutReceiptListCallback(outnoList);
//        Map<String, List<PickingOutVoReceiptListVo>> listMap = pickingOutVoReceiptList.stream().collect(Collectors.groupingBy(PickingOutVoReceiptListVo::getOutno));
//        for (PickingOutVo pickingOutVo : pickingOutCallback) {
//            //工单发出回调
////            this.workOrderIssue(pickingOutVo.getSfda014());
//            pickingOutVo.setActionType(Constant.ActionType_I);
//            pickingOutVo.setSfdadocno(Constant.PMDSDOCNO_5409);
//            pickingOutVo.setSfdasite(Constant.PMDSSITE_AMA);
//            List<PickingOutVoReceiptListVo> pickingOutVoReceiptListVoList = listMap.get(pickingOutVo.getSfda014());
//            List<PickingOutVoReceiptListReq> pickingOutVoReceiptListReqs = BeanUtil.copyToList(pickingOutVoReceiptListVoList, PickingOutVoReceiptListReq.class);
//            //分发项次项序  返回要修改的数据
//            List<AsyncWorkorderVo> asyncWorkorderVos = distributeItemOrder(pickingOutVoReceiptListReqs, pickingOutVo.getSfda014());
//            log.info(pickingOutVoReceiptListReqs.toString());
//            if (CollUtil.isEmpty(asyncWorkorderVos)) {
//                log.info("未获取到出库单工单信息跳出本次循环:出库单号:{}", pickingOutVo.getSfda014());
//                continue;
//            } else {
//                //查询库存管理特征
//                for (PickingOutVoReceiptListReq pickingOutVoReceiptListReq : pickingOutVoReceiptListReqs) {
//                    String inag003 = wmsPurchaseMapper.getInventoryInag003(pickingOutVoReceiptListReq);
//                    if (ObjectUtil.isNotEmpty(inag003)) {
//                        pickingOutVoReceiptListReq.setSfdc016(inag003);
//                    }
//                }
//            }
//
//            String resMessage = soapXmlUtil.getSoapXml("ReGetMaterial", "sfda_t", "sfdc_t", pickingOutVo, pickingOutVoReceiptListReqs);
//            try {
//                //转换为soap消息
//                MessageFactory msgFactory = MessageFactory.newInstance();
//                SOAPMessage message = msgFactory.createMessage();
//                SOAPPart soapPart = message.getSOAPPart();
//                byte[] buffer = resMessage.getBytes();
//                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
//                StreamSource source = new StreamSource(stream);
//                soapPart.setContent(source);
//                message.writeTo(System.out);
//                log.info(resMessage);
//
//                //发送soap消息，并解析结果
////                String result = soapXmlUtil.sendSoapMessage(message);
////                log.info("soap接口生产领料回调->{}", result);
////                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
////                if (xmlResp.getCode().equals("0")) {
////                    //更新相应表状态为已下发
////                    wmsPurchaseMapper.updateReGetMaterialCallback(pickingOutVo.getSfda014(), xmlResp.getData().get("sfdadocno"), 1);
////                    //更新工单表数据
////                    asyncWorkorderMapper.updateBatch(asyncWorkorderVos);
////                    //新增记录数据
////                    newRecordData(pickingOutVo.getSfda014(), pickingOutVoReceiptListReqs);
////                } else {
////                    //更新相应表状态为已下发
////                    wmsPurchaseMapper.updateReGetMaterialCallback(pickingOutVo.getSfda014(), xmlResp.getMessage(), 2);
////                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    private List<AsyncWorkorderVo> distributeItemOrder(List<PickingOutVoReceiptListReq> pickingOutVoReceiptListReqs, String outno) {
        //查询
        //获取工单号
        String workOrderNo = pickingOutVoReceiptListReqs.get(0).getSfdc001();
        List<String> mcodeList = pickingOutVoReceiptListReqs.stream().map(PickingOutVoReceiptListReq::getSfdc004).distinct().collect(Collectors.toList());
        //查询工单是否存在
        String asyncWorkorder = asyncWorkorderMapper.getAsyncWorkorder(workOrderNo);
        if (ObjectUtil.isEmpty(asyncWorkorder)) {
            log.error("单号工单信息未查到:{}", workOrderNo);
            //拉取工单信息到async_workorder
            asyncWorkorderMapper.updateAsyncWorkorder(workOrderNo);
            return null;
        }
        //获取工单信息
        List<AsyncWorkorderVo> distributeItemOrder = asyncWorkorderMapper.getDistributeItemOrder(workOrderNo, mcodeList);
        if (CollUtil.isEmpty(distributeItemOrder)) {
            //更新相应表状态为已下发
            wmsPurchaseMapper.updateReGetMaterialCallback(outno, workOrderNo + "工单发料数据已足够！本出库单未回写，请确认！", 2);
            return null;
        }
        List<PickingOutVoReceiptListReq> newPickingOutVoReceiptListReqs = new ArrayList<>();
        //分发工单信息
        for (PickingOutVoReceiptListReq pickingOutVoReceiptListReq : pickingOutVoReceiptListReqs) {
            //料号
            String sfdc004 = pickingOutVoReceiptListReq.getSfdc004();
            //数量
            BigDecimal sfdc007 = pickingOutVoReceiptListReq.getSfdc007();
            for (AsyncWorkorderVo asyncWorkorderVo : distributeItemOrder) {
                if (sfdc007.compareTo(BigDecimal.ZERO) == 0) {
                    break;
                }
                //料号相同时
                if (asyncWorkorderVo.getMcode().equals(sfdc004) && asyncWorkorderVo.getTotal().compareTo(asyncWorkorderVo.getNum()) > 0) {
                    //项次数量足够
                    if (asyncWorkorderVo.getTotal().compareTo(sfdc007.add(asyncWorkorderVo.getNum())) >= 0 && ObjectUtil.isEmpty(pickingOutVoReceiptListReq.getSfdc002())) {
                        asyncWorkorderVo.setNum(sfdc007.add(asyncWorkorderVo.getNum()));
                        //项次
                        pickingOutVoReceiptListReq.setSfdc002(asyncWorkorderVo.getItem());
                        //项序
                        pickingOutVoReceiptListReq.setSfdc003(asyncWorkorderVo.getTerm());
                        sfdc007 = BigDecimal.ZERO;
                        //领完数量不够时寻找下一个项次
                    } else {
                        //已经有项次时 获取下一个项次
                        if (ObjectUtil.isNotEmpty(pickingOutVoReceiptListReq.getSfdc002())) {
                            //剩余数量大于0 创建出一个新的出库单
                            if (sfdc007.compareTo(BigDecimal.ZERO) > 0) {
                                PickingOutVoReceiptListReq newReq = BeanUtil.copyProperties(pickingOutVoReceiptListReq, PickingOutVoReceiptListReq.class);
                                newReq.setSfdc007(sfdc007);
                                //项次
                                newReq.setSfdc002(asyncWorkorderVo.getItem());
                                //项序
                                newReq.setSfdc003(asyncWorkorderVo.getTerm());
                                if (asyncWorkorderVo.getTotal().compareTo(sfdc007.add(asyncWorkorderVo.getNum())) >= 0) {
                                    newReq.setSfdc007(sfdc007);
                                    asyncWorkorderVo.setNum(sfdc007.add(asyncWorkorderVo.getNum()));
                                    sfdc007 = BigDecimal.ZERO;
                                } else {
                                    //项次剩余要领取数量
                                    BigDecimal subtract = asyncWorkorderVo.getTotal().subtract(asyncWorkorderVo.getNum());
                                    newReq.setSfdc007(subtract);
                                    asyncWorkorderVo.setNum(asyncWorkorderVo.getTotal());
                                    //出库剩余数量
                                    sfdc007 = sfdc007.subtract(subtract);
                                }
                                newPickingOutVoReceiptListReqs.add(newReq);
                            }
                        } else {
                            //剩余要领取数量
                            BigDecimal subtract = asyncWorkorderVo.getTotal().subtract(asyncWorkorderVo.getNum());
                            asyncWorkorderVo.setNum(asyncWorkorderVo.getTotal());
                            //项次
                            pickingOutVoReceiptListReq.setSfdc002(asyncWorkorderVo.getItem());
                            //项序
                            pickingOutVoReceiptListReq.setSfdc003(asyncWorkorderVo.getTerm());
                            pickingOutVoReceiptListReq.setSfdc007(subtract);
                            //出库剩余数量
                            sfdc007 = sfdc007.subtract(subtract);
                        }
                    }
                }
            }
        }

        if (CollUtil.isNotEmpty(newPickingOutVoReceiptListReqs)) {
            pickingOutVoReceiptListReqs.addAll(newPickingOutVoReceiptListReqs);
        }

        //清除小于0的数据
        return distributeItemOrder.stream().filter(item -> item.getNum().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
    }
}
